package com.hzx.security.config;

import com.hzx.security.filter.TokenAuthFilter;
import com.hzx.security.filter.TokenLoginFilter;
import com.hzx.security.handler.TokenLogoutHandler;
import com.hzx.security.security.DefaultPasswordEncoder;
import com.hzx.security.security.TokenManager;
import com.hzx.security.security.UnauthEntryPoin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;

public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {

    private RedisTemplate redisTemplate;

    private TokenManager tokenManager;

    private DefaultPasswordEncoder defaultPasswordEncoder;

    private UserDetailsService userDetailsService;

    @Autowired
    public TokenWebSecurityConfig(RedisTemplate redisTemplate,TokenManager tokenManager,DefaultPasswordEncoder defaultPasswordEncoder, UserDetailsService userDetailsService){
        this.redisTemplate = redisTemplate;
        this.tokenManager = tokenManager;
        this.defaultPasswordEncoder = defaultPasswordEncoder;
        this.userDetailsService = userDetailsService;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling()
                .authenticationEntryPoint(new UnauthEntryPoin())//没有权限访问
                .and().csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and().logout().logoutUrl("/admin/acl/index/logout")
                .addLogoutHandler(new TokenLogoutHandler(tokenManager,redisTemplate))
                .and().addFilter(new TokenAuthFilter(authenticationManager() ,redisTemplate,tokenManager))
                .addFilter(new TokenLoginFilter(tokenManager,redisTemplate,authenticationManager())).httpBasic();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(defaultPasswordEncoder);
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/**");//不进行认证的路径，可以直接访问
    }
}
